﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XProject.DAO;
using XProject.Entity;
using XProject.GUI;
using XProject.Util;
using System.Configuration;
namespace XProject.GUI
{
    public partial class ContactManager : Form
    {
        PersonDAO daoPerson = new PersonDAO();
        ContactDAO daoContact = new ContactDAO();
        EventDAO daoEvent = new EventDAO();
        IList<Person> lstPerson = new List<Person>();
        int countTime = 0;
        public ContactManager()
        {
            InitializeComponent();
        }
        /// <summary>
        /// method to add an item to list view item
        /// </summary>
        /// <param name="person"></param>
        void AddListItem(Person person)
        {
            ListViewItem item = new ListViewItem(person.PersonID.ToString());
            item.SubItems.Add(person.Name);
            item.SubItems.Add(person.DateOfBirth.ToShortDateString());
            if(person.Contact!=null)
            item.SubItems.Add(person.Contact.Address);
            item.Tag = person;
            lsvPerson.Items.Add(item);
        }
        void CreatePhoneList(Person person)
        {            
            if (person.Contact.Phones.Count > 0)
            {
                foreach (Phone phone in person.Contact.Phones)
                {
                    cmbPhone.Items.Add(phone.PhoneNumber);
                }
                cmbPhone.SelectedIndex = 0; 
            }
        }
        void CreateEmailList(Person person)
        {
         
            if (person.Contact.Emails.Count > 0)
            {
                foreach (Email email in person.Contact.Emails)
                {
                    cmbEmail.Items.Add(email.EmailAddress);
                }
                cmbEmail.SelectedIndex = 0;
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'db1DataSet.Person' table. You can move, or remove it, as needed.
            //set icon
            //string icon = Application.StartupPath + "\\" + ConfigurationManager.AppSettings["icon"];
            //if (System.IO.File.Exists(icon)) { this.Icon = new Icon(icon); }
            //load data
            lstPerson=daoPerson.SelectAll();
            if (lstPerson.Count > 0)
            {
                foreach (Person person in lstPerson)
                {
                    AddListItem(person);
                }
                lstPerson.Clear();
            }

        }

        private void chkGender_CheckedChanged(object sender, EventArgs e)
        {
            if (!chkGender.Checked)
            {
                chkGender.Text = "Female";
            }
            else
            {
                chkGender.Text = "Male";
            }
        }

        private void lsvPerson_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lsvPerson.SelectedIndices.Count > 0)
            {
                Person person = lsvPerson.SelectedItems[0].Tag as Person;
                txtName.Text = person.Name;
                dtpDateOfBirth.Value = person.DateOfBirth;
                chkGender.Checked = person.Gender;
                txtNote.Text = person.Note;
                if (person.Contact != null)
                {
                    txtAddress.Text = person.Contact.Address;
                    cmbEmail.Items.Clear();
                    cmbPhone.Items.Clear();
                    cmbEmail.Text = "";
                    cmbPhone.Text = "";
                    CreatePhoneList(person);
                    CreateEmailList(person);
                }              
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (IsValidInput())
            {
                try
                {
                    Person person = new Person(txtName.Text, chkGender.Checked, dtpDateOfBirth.Value);
                    person.Contact.Address = txtAddress.Text;                  
                    Phone phone =new Phone(-1,cmbPhone.Text,new PhoneType(4),"");//n/a phone type
                    person.Contact.Phones.Add(phone);            
                    Email email = new Email(cmbEmail.Text);
                    person.Contact.Emails.Add(email);                  
                    person.Note = txtNote.Text;
                    if (daoPerson.Insert(person) > 0)
                    {
                        MessageBox.Show("Successed");
                        AddListItem(person);
                        txtAddress.Text = "";
                        txtName.Text = "";
                        txtNote.Text = "";
                        Event ev = new Event();
                        ev.Account = MainForm.CurrentAccount;
                        ev.Content = "sinh nhật của " + person.Name;
                        ev.StartTime = dtpDateOfBirth.Value;
                        ev.EndTime = dtpDateOfBirth.Value;
                        ev.Type.TypeID = 1; //birthday
                        ev.Priority = 2; //normal
                        ev.IsPublic = true;
                       daoEvent.Insert(ev);

                    }
                    else MessageBox.Show(daoPerson.Message);
                }
                catch (Exception ex) { }
            }
            else MessageBox.Show("Invalid input");
        }
        bool IsValidInput()
        {
            if (txtName.Text == "") return false;           
            if (dtpDateOfBirth.Value > DateTime.Now) return false;
            return true;
        }

        private void btnPhoneEdit_Click(object sender, EventArgs e)
        {
            if (lsvPerson.SelectedItems.Count <= 0)
            {
                MessageBox.Show("Please select an item");
                return;
            }
            PhoneManager frmPhone = new PhoneManager();
            Person person = lsvPerson.SelectedItems[0].Tag as Person;
            if (person != null) frmPhone.Contact = person.Contact;
            frmPhone.Text += " [" + person.Name + "]";
            frmPhone.ShowDialog();
        }

        private void btnEmailEdit_Click(object sender, EventArgs e)
        {
            if (lsvPerson.SelectedItems.Count <= 0)
            {
                MessageBox.Show("Please select an item");
                return;
            }
            EmailManager frmEmail = new EmailManager();
             Person person = lsvPerson.SelectedItems[0].Tag as Person;
            if (person != null) frmEmail.Contact = person.Contact;
            frmEmail.Text += " [" + person.Name + "]";
            frmEmail.ShowDialog();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (lsvPerson.SelectedIndices.Count <= 0)
            {
                MessageBox.Show("Please select an item");
                return;
            }
            if (MessageBox.Show("Are you sure want to modified this contact?","Confirm",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2) != DialogResult.Yes) return;
            Person person = lsvPerson.SelectedItems[0].Tag as Person;
            person.Name = txtName.Text;
            person.Gender = chkGender.Checked;
            person.DateOfBirth = dtpDateOfBirth.Value;
            person.Contact.Address = txtAddress.Text;
            person.Note = txtNote.Text;
            if (daoPerson.Update(person) > 0)
                if (daoContact.Update(person.Contact) > 0)
                {
                    MessageBox.Show("Updated successfully");
                    lsvPerson.SelectedItems[0].Tag = person;
                    lsvPerson.SelectedItems[0].SubItems[1].Text = person.Name;
                    lsvPerson.SelectedItems[0].SubItems[2].Text = person.DateOfBirth.ToShortDateString();
                    lsvPerson.SelectedItems[0].SubItems[3].Text = person.Contact.Address;
                }
                else MessageBox.Show(daoContact.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        else MessageBox.Show(daoPerson.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lsvPerson.SelectedIndices.Count <= 0)
            {
                MessageBox.Show("Please select an item");                
                return;
            }
            
            if (MessageBox.Show("Are you sure want to delete this contact?", "Confirm",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                Person person = lsvPerson.SelectedItems[0].Tag as Person;
                if (person.PersonID == MainForm.CurrentAccount.Person.PersonID)
                {
                    MessageBox.Show("You cannot delete your own contact because  the current account depend on it");
                    return;
                }
                if (daoPerson.Delete(person) > 0)
                {
                    MessageBox.Show("Deleted successfully");
                    lstPerson.Remove(person);
                    lsvPerson.Items.Remove(lsvPerson.SelectedItems[0]);
                }
                else MessageBox.Show(daoPerson.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {

            DoSearch();
        }

        private void txtSearch_Enter(object sender, EventArgs e)
        {
            if (lstPerson.Count == 0) lstPerson = daoPerson.SelectAll();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            countTime++;
            if(countTime>90)
            timer1.Stop();
    }

        private void cmbPhone_Enter(object sender, EventArgs e)
        {
            if (cmbPhone.Items.Count == 0) btnPhoneEdit_Click(sender, e);
        }

        private void cmbEmail_Enter(object sender, EventArgs e)
        {
            if (cmbEmail.Items.Count == 0) btnEmailEdit_Click(sender,e);
        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                DoSearch();
            }
        }
        void DoSearch()
        {
            int mode = 0;
            string st = txtSearch.Text.Trim();            
            if (st.StartsWith("email:")) { mode = 1; st = st.Remove(0, 6); }
            else if (st.StartsWith("phone:")) { mode = 2; st = st.Remove(0, 6); }
            lsvPerson.Items.Clear();
            st = st.Trim();
            foreach (Entity.Person person in lstPerson)
            {
                if (mode == 0)
                {
                    if (person.Name.ToLower().Contains(st))
                    {
                        AddListItem(person);
                    }
                }
                else if (mode == 1)
                {
                    if (person.Contact.ContainEmail(st))
                    {
                        AddListItem(person);
                    }
                }
                else if (mode == 2)
                {
                    if (person.Contact.ContainPhone(st))
                    {
                        AddListItem(person);
                    }
                }

            }
            //after do search
            if (countTime > 90)
            {
                lstPerson.Clear();
                countTime = 0;
            }
            if (timer1.Enabled == false) timer1.Start();
        }
    }
}